package com.mb.collect.service;



import com.mb.collect.mapper.CollectMapper;
import com.mb.common.pojo.Collect;
import com.mb.common.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class CollectService {

    @Autowired(required = false)
    private CollectMapper collectMapper;

    @Autowired
    private RestTemplate restTemplate;

    public List<Collect> queryMyCarts(String userId) {
        return collectMapper.selectId(userId);
    }

    public void addCollect(Collect collect) {
        /*
        * 1.查询新增购物车是否存在
        * 2.不存在 —— 新增
        * 3.存  在 —— 更新数据
        * */
        Collect exit = collectMapper.selectUserIdAndProductId(collect);

        if(exit==null){
            //为空 则补齐对象  写入数据库
//            String url="http://productservice/product/manage/item/"+cart.getProductId();
//            Product product = restTemplate.getForObject(url, Product.class);

            Product product = collectMapper.selectProductById(collect.getProductId());

            collect.setProductName(product.getProductName());
            collect.setProductPrice(product.getProductPrice());
            collect.setProductImage(product.getProductImgurl());
            //将insert写入数据库
            collectMapper.insertCollect(collect);
        }else {
           /* //不为空查到了这个商品
            int num = collect.getNum();
            int oldnum = exit.getNum();
            collect.setNum(num+oldnum);
            collectMapper.updateNum(collect);*/
            delCollect(collect);
        }
    }

    public void delCollect(Collect collect) {
        collectMapper.delCollect(collect);
    }


    public List<Collect> queryMycollect(String userId) {
        return collectMapper.selectId(userId);
    }

}
